//index.js
const tfl = require('@tensorflow/tfjs-layers');
const tf = require('@tensorflow/tfjs-core');
import request from '../../utils/request'
const app = getApp()
import intro from '../../utils/intro'
Page({
  data: {
    model:{},
    classes:[],
    previewImgSrc:'',
  },
  onLoad : async function () {
    // 载入tensorflow模型
    const DATA_URL = 'https://7463-tcb-csq0wy5b65eabf-0d365c00ed906-1306152027.tcb.qcloud.la'
    const model = await tfl.loadLayersModel(DATA_URL + '/model.json')
    // model.summary();
    const classes = await request(DATA_URL + '/classes.json').then(res => res.data)
    this.data.classes= classes;
    // 使用同步设置不用通过视图渲染
    this.data.model = model;
  },
  uploadImage: async function  () {
    let _this = this;
    wx.chooseImage({
      count:1,
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera']
    }).then((res) => {
      const tempFilePath= res.tempFilePaths[0];
      this.setData({previewImgSrc : tempFilePath });

      this.imgPath2x(tempFilePath);
      // pred.print()
      // this.results = pred.arraySync()[0]
      // .map((score,i) => ({ score: Math.round(score * 10000,2)/100, label :this.classes[i], ...intro[this.classes[i]]}))
      // .sort((a,b) => b.score-a.score)

      // this.result = results && {..., ...intro[results[0].label]}
      // console.log(this.results)
    })
  },
  readFilePath: function (imgPath){
     const fs = wx.getFileSystemManager();
    //  return fs.readFileSync(imgPath, 'base64', 0);
    return fs.readFileSync(imgPath, 'utf8', 0);
  },
  imgPath2x: function(imgPath){
    // tf.tidy 及时清理转换后的内存
    const _this = this
     const buffer = this.readFilePath(imgPath);
     const query = wx.createSelectorQuery()
      query.select('#img').boundingClientRect()
      // query.selectViewport().scrollOffset()
      return query.exec((res) =>{
        const imgData = {data: new Uint8Array(buffer), width: res[0].width, height: res[0].height}
        const pred = tf.tidy(() => {
          const imgTsResized = tf.browser.fromPixels(imgData).slice([0,0,0],[-1,-1,3])
          // const imgTsResized = tf.image.resizeBilinear(imgTs, [224,224])
          const tensor = imgTsResized.toFloat().sub(255/2).div(255/2).reshape([1,224,224,3])
          // console.log("this.data.model",this.data.model)
          const pred = this.data.model.predict(tensor)
          return 	pred		
        })
        console.log("pred",pred)
        // const x = this.imgPath2x(tempFilePath)
        // console.log("x",x)
        pred.print()
        const results = pred.arraySync()[0]
          .map((score,i) => ({ score: Math.round(score * 10000,2)/100, label :this.data.classes[i], ...intro[this.data.classes[i]]}))
          .sort((a,b) => b.score-a.score)
          console.log(results)
          _this.setData({results})
      })
 },


})
